{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Biome Level statistics for model: SD1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites and images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the basic maps that needed for the analysis\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the root shoot ratio map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "# load the two composites tha will be used in the analysis\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\")\n",
    "# load the biome layer \n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "# define a pixel area layer with unit km2\n",
    "pixelAreaMap = ee.Image.pixelArea().divide(10000);\n",
    "# define the boundary geography reference\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Load the biomass density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "potentialDensity = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_SD1_Potential_density_Ensambled_Mean\").unmask()\n",
    "presentDensity =  ee.Image(\"users/leonidmoore/ForestBiomass/RemoteSensingModel/ESA_CCI_AGB_Map_bias_corrected_1km_2010\").unmask().multiply(carbonConcentration)\n",
    "\n",
    "# define the standard projection\n",
    "stdProj = potentialDensity.projection()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Adjust the present and potential density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask= presentForestCover.gt(0)\n",
    "potentialMask= potentialCoverAdjusted.gt(0)\n",
    "\n",
    "# check the difference of the two density maps\n",
    "potentialHigher = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).gte(0)\n",
    "potentialLower = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "agbPotentialDensity = presentDensity.multiply(potentialLower).add(potentialDensity.multiply(potentialHigher))\n",
    "# add the root biomass to the AGB to get TGB\n",
    "tgbPotentialDensity = agbPotentialDensity.multiply(rootShootRatio).add(agbPotentialDensity)\n",
    "tgbPresentDensity = presentDensity.multiply(rootShootRatio).add(presentDensity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Partioning the potential cover into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load all the landuse type layers\n",
    "croplandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/cropland_Percent\").rename('cropland').divide(100).reproject(crs=stdProj);\n",
    "grazingOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/grazing_Percent\").rename('grazing').divide(100).reproject(crs=stdProj);\n",
    "pastureOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/pasture_Percent\").rename('pasture').divide(100).reproject(crs=stdProj);\n",
    "rangelandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/rangeland_Percent\").rename('rangeland').divide(100).reproject(crs=stdProj);\n",
    "urbanOrg = compositeImage.select(['LandCoverClass_Urban_Builtup']).divide(100).unmask().reproject(crs=stdProj);\n",
    "snowIceOrg = compositeImageNew.select(['ConsensusLandCoverClass_Snow_Ice']).divide(100).unmask().reproject(crs=stdProj);\n",
    "openWaterOrg = compositeImageNew.select(['ConsensusLandCoverClass_Open_Water']).divide(100).unmask().reproject(crs=stdProj);\n",
    "# define the total landcover types\n",
    "sumCover = presentForestCover.add(pastureOrg).add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(openWaterOrg).add(snowIceOrg);\n",
    "oneSubtract = ee.Image(1).subtract(sumCover);\n",
    "freeland = oneSubtract.multiply(oneSubtract.gte(0));\n",
    "# get the scale ratio for pixels with sumCover larger than 1\n",
    "scaleRatio = ee.Image(1).subtract(presentForestCover).divide(sumCover.subtract(presentForestCover)).multiply(oneSubtract.lt(0));\n",
    "# get the ratio of these three disturbed maps\n",
    "pasture = pastureOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(pastureOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "rangeland = rangelandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(rangelandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "cropland = croplandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(croplandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "urban = urbanOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(urbanOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "openWater = openWaterOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(openWaterOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "snowIce = snowIceOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(snowIceOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "sumTT = presentForestCover.add(pasture).add(rangeland).add(cropland).add(urban).add(freeland).add(openWater).add(snowIce).unmask();\n",
    "\n",
    "effectivePotentialMask = freeland.add(rangeland).add(pasture).add(cropland).add(urban).gt(0);\n",
    "# there are some pixels without any landcover survived but with open water and ice and snow. here we mask these pixels out\n",
    "sumlandCover = pastureOrg.add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(freeland);\n",
    "restorationMap = potentialCoverAdjusted.subtract(presentForestCover).mask(effectivePotentialMask).unmask();\n",
    "\n",
    "# sum all these scaled layersv\n",
    "scaledSum = pasture.add(rangeland).add(cropland).add(urban).add(freeland);\n",
    "potentialCoverFinal = restorationMap.add(presentForestCover);\n",
    "# allocate the potential equally to each layer\n",
    "freelandPotentialCover = freeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "rangelandPotentialCover = rangeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "pasturePotentialCover = pasture.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "croplandPotentialCover = cropland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "urbanPotentialCover = urban.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "#  allocate the freeland potential in pixels with forest cover larger than 10% to conservation potential\n",
    "freelandForConsevation = freelandPotentialCover.multiply(presentForestCover.gte(0.1)).unmask();\n",
    "maximumPotentialCover = freelandForConsevation.add(presentForestCover);\n",
    "# calucate the reall freeland outside of forest\n",
    "freelandLeftMap = freelandPotentialCover.subtract(freelandForConsevation).unmask()# the left positive pixels are real freeland pixels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Partioning the biomass potential into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the existing carbon, present potential carbon and absolute potential carbon in forests\n",
    "absoluteImage1 = tgbPresentDensity.multiply(pixelAreaMap).multiply(presentMask).divide(1000000000).rename('Present')\n",
    "absoluteImage3 = tgbPotentialDensity.multiply(pixelAreaMap).multiply(potentialCoverFinal.gt(0)).divide(1000000000).rename('AbsolutePotential')\n",
    "# get the sum of the potential covers\n",
    "potentialCoverSum = freelandLeftMap.add(rangelandPotentialCover).add(pasturePotentialCover).add(croplandPotentialCover).add(urbanPotentialCover)\n",
    "\n",
    "trueRestorationPotential = absoluteImage3.subtract(absoluteImage1).multiply(1000000000)\n",
    "ratioPotentialBiomassDensity = absoluteImage1.multiply(potentialCoverFinal.divide(presentForestCover))\n",
    "#  get the real for conservation potential\n",
    "realDensityIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).gt(0)).unmask()\n",
    "realDensityNotIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).lte(0)).unmask()\n",
    "trueReforestationPotential = realDensityNotIncreased.add(realDensityIncreased.multiply(ee.Image(1).subtract(presentForestCover.divide(potentialCoverFinal))))\n",
    "\n",
    "conservationPotentialPart1 = realDensityIncreased.multiply(presentForestCover.add(freelandForConsevation).divide(potentialCoverFinal))\n",
    "conservationPotentialPart2 = realDensityNotIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal.subtract(presentForestCover)))\n",
    "\n",
    "# calculate the part of the potential inside the forest cover which was allocate to conservation potential.\n",
    "freelandForConservation1 = realDensityIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal))\n",
    "freelandForConservation = freelandForConservation1.add(conservationPotentialPart2).rename('FreeToConservation')\n",
    "\n",
    "absoluteImage2 = conservationPotentialPart1.add(conservationPotentialPart2).add(absoluteImage1).rename('PresentPotential')\n",
    "\n",
    "trueReforestationPotential = absoluteImage3.subtract(absoluteImage2)\n",
    "\n",
    "absoluteImage4 = trueReforestationPotential.multiply(freelandLeftMap.divide(potentialCoverSum)).rename('FreelandPotential')\n",
    "absoluteImage5 = trueReforestationPotential.multiply(rangelandPotentialCover.divide(potentialCoverSum)).rename('RangelandPotential')\n",
    "absoluteImage6 = trueReforestationPotential.multiply(pasturePotentialCover.divide(potentialCoverSum)).rename('PasturePotential')\n",
    "absoluteImage7 = trueReforestationPotential.multiply(croplandPotentialCover.divide(potentialCoverSum)).rename('CroplandPotential')\n",
    "absoluteImage8 = trueReforestationPotential.multiply(urbanPotentialCover.divide(potentialCoverSum)).rename('UrbanPotential')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate the potential numbers and write into local folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>186.488539</td>\n",
       "      <td>221.017653</td>\n",
       "      <td>239.393689</td>\n",
       "      <td>3.320571</td>\n",
       "      <td>0.056396</td>\n",
       "      <td>6.558734</td>\n",
       "      <td>8.229498</td>\n",
       "      <td>0.210838</td>\n",
       "      <td>5.841856</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6.459329</td>\n",
       "      <td>8.763745</td>\n",
       "      <td>14.070485</td>\n",
       "      <td>1.255663</td>\n",
       "      <td>0.013650</td>\n",
       "      <td>1.364883</td>\n",
       "      <td>2.640010</td>\n",
       "      <td>0.032534</td>\n",
       "      <td>0.531654</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2.530593</td>\n",
       "      <td>3.368252</td>\n",
       "      <td>4.016980</td>\n",
       "      <td>0.208667</td>\n",
       "      <td>0.018173</td>\n",
       "      <td>0.253933</td>\n",
       "      <td>0.165781</td>\n",
       "      <td>0.002176</td>\n",
       "      <td>0.242059</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>45.220397</td>\n",
       "      <td>52.243392</td>\n",
       "      <td>67.394806</td>\n",
       "      <td>3.400594</td>\n",
       "      <td>0.020217</td>\n",
       "      <td>4.481972</td>\n",
       "      <td>6.904577</td>\n",
       "      <td>0.344055</td>\n",
       "      <td>2.384873</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>23.560230</td>\n",
       "      <td>25.609106</td>\n",
       "      <td>27.691773</td>\n",
       "      <td>0.904275</td>\n",
       "      <td>0.032824</td>\n",
       "      <td>0.674021</td>\n",
       "      <td>0.442024</td>\n",
       "      <td>0.029523</td>\n",
       "      <td>0.992524</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>57.746120</td>\n",
       "      <td>67.010051</td>\n",
       "      <td>70.401523</td>\n",
       "      <td>3.000055</td>\n",
       "      <td>0.000917</td>\n",
       "      <td>0.202154</td>\n",
       "      <td>0.177860</td>\n",
       "      <td>0.010487</td>\n",
       "      <td>3.981694</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>38.736434</td>\n",
       "      <td>53.345726</td>\n",
       "      <td>78.517872</td>\n",
       "      <td>5.119538</td>\n",
       "      <td>8.713384</td>\n",
       "      <td>6.595741</td>\n",
       "      <td>4.695026</td>\n",
       "      <td>0.048458</td>\n",
       "      <td>3.656071</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>5.378404</td>\n",
       "      <td>6.377587</td>\n",
       "      <td>21.708118</td>\n",
       "      <td>2.813265</td>\n",
       "      <td>4.943919</td>\n",
       "      <td>2.017584</td>\n",
       "      <td>5.483373</td>\n",
       "      <td>0.072391</td>\n",
       "      <td>0.185973</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.496285</td>\n",
       "      <td>2.187372</td>\n",
       "      <td>3.134292</td>\n",
       "      <td>0.271620</td>\n",
       "      <td>0.330218</td>\n",
       "      <td>0.185545</td>\n",
       "      <td>0.152058</td>\n",
       "      <td>0.007479</td>\n",
       "      <td>0.105242</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2.963950</td>\n",
       "      <td>4.150252</td>\n",
       "      <td>8.037884</td>\n",
       "      <td>1.063367</td>\n",
       "      <td>1.733853</td>\n",
       "      <td>0.556240</td>\n",
       "      <td>0.527437</td>\n",
       "      <td>0.006735</td>\n",
       "      <td>0.174499</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>5.279083</td>\n",
       "      <td>7.667322</td>\n",
       "      <td>11.383183</td>\n",
       "      <td>3.708592</td>\n",
       "      <td>0.001243</td>\n",
       "      <td>0.000506</td>\n",
       "      <td>0.005229</td>\n",
       "      <td>0.000292</td>\n",
       "      <td>0.389910</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2.799836</td>\n",
       "      <td>3.926185</td>\n",
       "      <td>8.175020</td>\n",
       "      <td>1.119082</td>\n",
       "      <td>0.015665</td>\n",
       "      <td>1.454600</td>\n",
       "      <td>1.604865</td>\n",
       "      <td>0.054624</td>\n",
       "      <td>0.285374</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>1.813424</td>\n",
       "      <td>2.873024</td>\n",
       "      <td>22.137975</td>\n",
       "      <td>9.098089</td>\n",
       "      <td>7.643699</td>\n",
       "      <td>0.720323</td>\n",
       "      <td>1.759636</td>\n",
       "      <td>0.043203</td>\n",
       "      <td>0.238958</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.338357</td>\n",
       "      <td>2.042746</td>\n",
       "      <td>2.381823</td>\n",
       "      <td>0.116862</td>\n",
       "      <td>0.000967</td>\n",
       "      <td>0.066558</td>\n",
       "      <td>0.145316</td>\n",
       "      <td>0.009374</td>\n",
       "      <td>0.115846</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>381.810981</td>\n",
       "      <td>460.582412</td>\n",
       "      <td>578.445425</td>\n",
       "      <td>35.400240</td>\n",
       "      <td>23.525124</td>\n",
       "      <td>25.132793</td>\n",
       "      <td>32.932689</td>\n",
       "      <td>0.872167</td>\n",
       "      <td>19.126532</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    186.488539        221.017653         239.393689           3.320571   \n",
       "1      6.459329          8.763745          14.070485           1.255663   \n",
       "2      2.530593          3.368252           4.016980           0.208667   \n",
       "3     45.220397         52.243392          67.394806           3.400594   \n",
       "4     23.560230         25.609106          27.691773           0.904275   \n",
       "5     57.746120         67.010051          70.401523           3.000055   \n",
       "6     38.736434         53.345726          78.517872           5.119538   \n",
       "7      5.378404          6.377587          21.708118           2.813265   \n",
       "8      1.496285          2.187372           3.134292           0.271620   \n",
       "9      2.963950          4.150252           8.037884           1.063367   \n",
       "10     5.279083          7.667322          11.383183           3.708592   \n",
       "11     2.799836          3.926185           8.175020           1.119082   \n",
       "12     1.813424          2.873024          22.137975           9.098089   \n",
       "13     1.338357          2.042746           2.381823           0.116862   \n",
       "sum  381.810981        460.582412         578.445425          35.400240   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.056396          6.558734           8.229498        0.210838   \n",
       "1              0.013650          1.364883           2.640010        0.032534   \n",
       "2              0.018173          0.253933           0.165781        0.002176   \n",
       "3              0.020217          4.481972           6.904577        0.344055   \n",
       "4              0.032824          0.674021           0.442024        0.029523   \n",
       "5              0.000917          0.202154           0.177860        0.010487   \n",
       "6              8.713384          6.595741           4.695026        0.048458   \n",
       "7              4.943919          2.017584           5.483373        0.072391   \n",
       "8              0.330218          0.185545           0.152058        0.007479   \n",
       "9              1.733853          0.556240           0.527437        0.006735   \n",
       "10             0.001243          0.000506           0.005229        0.000292   \n",
       "11             0.015665          1.454600           1.604865        0.054624   \n",
       "12             7.643699          0.720323           1.759636        0.043203   \n",
       "13             0.000967          0.066558           0.145316        0.009374   \n",
       "sum           23.525124         25.132793          32.932689        0.872167   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              5.841856  \n",
       "1              0.531654  \n",
       "2              0.242059  \n",
       "3              2.384873  \n",
       "4              0.992524  \n",
       "5              3.981694  \n",
       "6              3.656071  \n",
       "7              0.185973  \n",
       "8              0.105242  \n",
       "9              0.174499  \n",
       "10             0.389910  \n",
       "11             0.285374  \n",
       "12             0.238958  \n",
       "13             0.115846  \n",
       "sum           19.126532  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD1_Biome_Level_Statistics.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>227.523114</td>\n",
       "      <td>269.651231</td>\n",
       "      <td>292.071889</td>\n",
       "      <td>4.051430</td>\n",
       "      <td>0.068965</td>\n",
       "      <td>8.002336</td>\n",
       "      <td>10.040704</td>\n",
       "      <td>0.257224</td>\n",
       "      <td>7.127535</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>7.880397</td>\n",
       "      <td>10.691745</td>\n",
       "      <td>17.166102</td>\n",
       "      <td>1.531920</td>\n",
       "      <td>0.016750</td>\n",
       "      <td>1.665208</td>\n",
       "      <td>3.220788</td>\n",
       "      <td>0.039691</td>\n",
       "      <td>0.648609</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.088217</td>\n",
       "      <td>4.110313</td>\n",
       "      <td>4.901802</td>\n",
       "      <td>0.254594</td>\n",
       "      <td>0.022146</td>\n",
       "      <td>0.309780</td>\n",
       "      <td>0.202314</td>\n",
       "      <td>0.002655</td>\n",
       "      <td>0.295397</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>60.141477</td>\n",
       "      <td>69.478856</td>\n",
       "      <td>89.627697</td>\n",
       "      <td>4.521759</td>\n",
       "      <td>0.026845</td>\n",
       "      <td>5.960509</td>\n",
       "      <td>9.182204</td>\n",
       "      <td>0.457525</td>\n",
       "      <td>3.170976</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>31.333880</td>\n",
       "      <td>34.058203</td>\n",
       "      <td>36.826151</td>\n",
       "      <td>1.201723</td>\n",
       "      <td>0.043353</td>\n",
       "      <td>0.896100</td>\n",
       "      <td>0.587530</td>\n",
       "      <td>0.039243</td>\n",
       "      <td>1.319761</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>103.902230</td>\n",
       "      <td>120.568252</td>\n",
       "      <td>126.668306</td>\n",
       "      <td>5.397960</td>\n",
       "      <td>0.001536</td>\n",
       "      <td>0.363125</td>\n",
       "      <td>0.318616</td>\n",
       "      <td>0.018815</td>\n",
       "      <td>7.164297</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>47.259514</td>\n",
       "      <td>65.082542</td>\n",
       "      <td>95.793050</td>\n",
       "      <td>6.245903</td>\n",
       "      <td>10.630566</td>\n",
       "      <td>8.046951</td>\n",
       "      <td>5.727969</td>\n",
       "      <td>0.059120</td>\n",
       "      <td>4.460374</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>7.153926</td>\n",
       "      <td>8.482845</td>\n",
       "      <td>28.870953</td>\n",
       "      <td>3.741336</td>\n",
       "      <td>6.574479</td>\n",
       "      <td>2.683218</td>\n",
       "      <td>7.292802</td>\n",
       "      <td>0.096273</td>\n",
       "      <td>0.247379</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.826047</td>\n",
       "      <td>2.669304</td>\n",
       "      <td>3.824737</td>\n",
       "      <td>0.331429</td>\n",
       "      <td>0.402859</td>\n",
       "      <td>0.226424</td>\n",
       "      <td>0.185587</td>\n",
       "      <td>0.009135</td>\n",
       "      <td>0.128426</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>3.935717</td>\n",
       "      <td>5.510920</td>\n",
       "      <td>10.677674</td>\n",
       "      <td>1.412999</td>\n",
       "      <td>2.304610</td>\n",
       "      <td>0.739249</td>\n",
       "      <td>0.700942</td>\n",
       "      <td>0.008953</td>\n",
       "      <td>0.231729</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>9.499304</td>\n",
       "      <td>13.796716</td>\n",
       "      <td>20.484012</td>\n",
       "      <td>6.674224</td>\n",
       "      <td>0.002230</td>\n",
       "      <td>0.000909</td>\n",
       "      <td>0.009408</td>\n",
       "      <td>0.000525</td>\n",
       "      <td>0.701569</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>3.388736</td>\n",
       "      <td>4.752010</td>\n",
       "      <td>9.893902</td>\n",
       "      <td>1.354269</td>\n",
       "      <td>0.019027</td>\n",
       "      <td>1.760321</td>\n",
       "      <td>1.942167</td>\n",
       "      <td>0.066108</td>\n",
       "      <td>0.345416</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.194913</td>\n",
       "      <td>3.477208</td>\n",
       "      <td>26.790667</td>\n",
       "      <td>11.009796</td>\n",
       "      <td>9.249950</td>\n",
       "      <td>0.871958</td>\n",
       "      <td>2.129472</td>\n",
       "      <td>0.052284</td>\n",
       "      <td>0.289213</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.632809</td>\n",
       "      <td>2.492166</td>\n",
       "      <td>2.905842</td>\n",
       "      <td>0.142567</td>\n",
       "      <td>0.001179</td>\n",
       "      <td>0.081208</td>\n",
       "      <td>0.177285</td>\n",
       "      <td>0.011436</td>\n",
       "      <td>0.141332</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>510.760280</td>\n",
       "      <td>614.822312</td>\n",
       "      <td>766.502784</td>\n",
       "      <td>47.871909</td>\n",
       "      <td>29.364495</td>\n",
       "      <td>31.607294</td>\n",
       "      <td>41.717789</td>\n",
       "      <td>1.118986</td>\n",
       "      <td>26.272012</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    227.523114        269.651231         292.071889           4.051430   \n",
       "1      7.880397         10.691745          17.166102           1.531920   \n",
       "2      3.088217          4.110313           4.901802           0.254594   \n",
       "3     60.141477         69.478856          89.627697           4.521759   \n",
       "4     31.333880         34.058203          36.826151           1.201723   \n",
       "5    103.902230        120.568252         126.668306           5.397960   \n",
       "6     47.259514         65.082542          95.793050           6.245903   \n",
       "7      7.153926          8.482845          28.870953           3.741336   \n",
       "8      1.826047          2.669304           3.824737           0.331429   \n",
       "9      3.935717          5.510920          10.677674           1.412999   \n",
       "10     9.499304         13.796716          20.484012           6.674224   \n",
       "11     3.388736          4.752010           9.893902           1.354269   \n",
       "12     2.194913          3.477208          26.790667          11.009796   \n",
       "13     1.632809          2.492166           2.905842           0.142567   \n",
       "sum  510.760280        614.822312         766.502784          47.871909   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.068965          8.002336          10.040704        0.257224   \n",
       "1              0.016750          1.665208           3.220788        0.039691   \n",
       "2              0.022146          0.309780           0.202314        0.002655   \n",
       "3              0.026845          5.960509           9.182204        0.457525   \n",
       "4              0.043353          0.896100           0.587530        0.039243   \n",
       "5              0.001536          0.363125           0.318616        0.018815   \n",
       "6             10.630566          8.046951           5.727969        0.059120   \n",
       "7              6.574479          2.683218           7.292802        0.096273   \n",
       "8              0.402859          0.226424           0.185587        0.009135   \n",
       "9              2.304610          0.739249           0.700942        0.008953   \n",
       "10             0.002230          0.000909           0.009408        0.000525   \n",
       "11             0.019027          1.760321           1.942167        0.066108   \n",
       "12             9.249950          0.871958           2.129472        0.052284   \n",
       "13             0.001179          0.081208           0.177285        0.011436   \n",
       "sum           29.364495         31.607294          41.717789        1.118986   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              7.127535  \n",
       "1              0.648609  \n",
       "2              0.295397  \n",
       "3              3.170976  \n",
       "4              1.319761  \n",
       "5              7.164297  \n",
       "6              4.460374  \n",
       "7              0.247379  \n",
       "8              0.128426  \n",
       "9              0.231729  \n",
       "10             0.701569  \n",
       "11             0.345416  \n",
       "12             0.289213  \n",
       "13             0.141332  \n",
       "sum           26.272012  "
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "\n",
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask).multiply(deadWoodLitterRatio)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum()\n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD1_Biome_Level_Statistics_with_Litter.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
